package btb.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.esotericsoftware.minlog.Log;

public class CDatabase {
	public static final String DEFAULT_HOST 	= "localhost";
	public static final String DEFAULT_USER		= "root";
	public static final String DEFAULT_PASS		= "";
	
	public static final String DEFAULT_DRIVER	= "com.mysql.jdbc.Driver";
	public static final String DEFAULT_URL		= "jdbc:mysql://localhost:3306/mysql";
	
	protected Connection connection = null;
	protected String host = DEFAULT_HOST;
	protected String user = DEFAULT_USER;
	protected String pass = DEFAULT_PASS;
	
	protected String driver = DEFAULT_DRIVER;
	protected String url = DEFAULT_URL;
	
	public CDatabase() throws ClassNotFoundException {
		Class.forName(this.driver);
	}
	
	public boolean connect()
	{
		boolean success = false;
		
		try
		{
			this.connection = DriverManager.getConnection(this.url, this.user, this.pass);
			success = true;
		}
		catch(SQLException e)
		{
			if(Log.DEBUG)
				Log.debug("database", "Connect() failure: DriverManager.getConnection tried, SQLException caught.");
		}
		
		return success;
	}
	
	public int executeUpdate(String _sql) {
		int result = -1;
		
		try {
			Statement statement = this.connection.createStatement();
			result = statement.executeUpdate(_sql);
		} catch (SQLException sqle) {
			
		}
		
		return result;
	}
	
	public ResultSet executeQuery(String _sql) {
		ResultSet resultSet = null;
		
		try
		{
			Statement statement = this.connection.createStatement();
			resultSet = statement.executeQuery(_sql);
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		}
		
		return resultSet;
	}
	
	public String getItem(String _table, String _item, String _where) {
		String value = "";
		String sql = "SELECT " + _item + " FROM " + _table + ((_where != null) ? " WHERE " + _where : "");
				
		ResultSet resultSet = this.executeQuery(sql);
		
		try {
			resultSet.next();
			value = resultSet.getString(_item);
			resultSet.close();
		} catch (SQLException e) {
			
		}
		
		return value;
	}
	
	public String getHost() {
		return this.host;
	}
	
	public String getUser() {
		return this.user;
	}
	
	public String getPass() {
		return this.pass;
	}
	
	public void setHost(String _host) {
		this.host = _host;
	}
	
	public void setUser(String _user) {
		this.user = _user;
	}
	
	public void setPass(String _pass) {
		this.pass = _pass;
	}
}
